<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true" :model="queryParams" ref="queryParams">
        <el-form-item label="表名称">
          <el-input
            v-model="queryParams.tableName"
            name="code"
            placeholder="请输入表名称"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="表描述">
          <el-input
            v-model="queryParams.tableComment"
            placeholder="请输入表描述"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">
            查询
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="queryParams = {};handleQuery()"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <vxe-toolbar custom>
      <template #buttons>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="handleGenTable"
          :disabled="selectTableIds.length <= 0"
        >
          生成
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="openImportTable"
        >
          导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-delete"
          @click="handleDelete"
          :disabled="selectTableIds.length <= 0"
        >
          删除
        </el-button>
      </template>
    </vxe-toolbar>

    <vxe-table
      ref="genCodeTableRef"
      :data="tableData"
      @checkbox-change="checkboxChangeHandle"
      @checkbox-all="checkboxAllHandle"
      :loading="tableLoading"
      :highlight-current-row="true"
      :highlight-hover-row="true"
      :highlight-current-column="true"
      :highlight-hover-column="true"
    >
      <vxe-column type="checkbox" width="60" align="center" />
      <vxe-column field="tableName" title="表名称" show-overflow />
      <vxe-column field="tableComment" title="表描述" show-overflow />
      <vxe-column field="className" title="实体类" show-overflow />
      <vxe-column field="createTime" title="创建时间" show-overflow />
      <vxe-column field="updateTime" title="更新时间" show-overflow />

      <vxe-column title="操作" align="center" min-width="200">
        <template v-slot="{ row }">
          <el-button
            type="text"
            icon="el-icon-view"
            @click="handlePreview(row)"
          >
            预览
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleEditTable(row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button
            type="text"
            icon="el-icon-refresh"
            @click="handleSynchDb(row)"
          >
            同步
          </el-button>
          <el-button
            type="text"
            icon="el-icon-download"
            @click="handleGenTable(row)"
          >
            生成代码
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <vxe-pager
      v-if="total > 0"
      class="qm-table-el-pager"
      :current-page="queryParams.pageNum"
      :page-size="queryParams.pageSize"
      :total="total"
      :pageSizes="[5, 10, 20, 50, 100]"
      @page-change="handlePageChange"
    />

    <!-- 导入表 -->
    <vxe-modal
      v-model="importModalVisible"
      :resize="true"
      width="1024"
      height="600"
      title="导入表"
      show-zoom
      destroy-on-close
      :loading="importModalLoading"
      :showFooter="true"
    >
      <gen-import @selectRowsEvent="importSelectRowsHandle" />
      <template v-slot:footer>
        <el-button type="primary" @click="importModalConfirm">确定</el-button>
        <el-button type="info" @click="importModalVisible = false"
          >取消</el-button
        >
      </template>
    </vxe-modal>

    <!-- 代码预览 -->
    <vxe-modal
      v-model="previewModalVisible"
      width="1024"
      height="600"
      title="代码预览"
      show-zoom
      destroy-on-close
      :showFooter="false"
      :loading="previewModalLoading"
    >
      <gen-preview :previewTableId="previewTableId" />
    </vxe-modal>

    <!-- 修改生成配置 -->
    <vxe-modal
      v-model="editModalVisible"
      width="1024"
      height="600"
      title="修改生成配置"
      show-zoom
      destroy-on-close
      :showFooter="false"
      :loading="editModalLoading"
    >
      <gen-edit
        :genEditTableId="genEditTableId"
        @genEditCloseEvent="genEditCloseHandle"
      />
    </vxe-modal>
  </div>
</template>

<script>
import GenImport from "./genImport";
import GenEdit from "./genEdit";
import GenPreview from "./genPreview";
import request from "@/utils/request";
import { downLoadZip } from "@/utils/zipdownload";

const ZIP_GEN_TYPE_KEY = "1";

export default {
  name: "GenCode",
  components: { GenImport, GenEdit, GenPreview },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: undefined,
        tableComment: undefined,
      },
      tableData: [],
      total: 0,
      tableLoading: false,
      importModalVisible: false,
      importModalLoading: false,
      previewModalVisible: false,
      previewModalLoading: false,
      editModalVisible: false,
      editModalLoading: false,
      importTableSelectRows: [],
      selectTableIds: [],
      selectTableNames: [],
      genEditTableId: undefined,
      previewTableId: undefined,
    };
  },
  created() {
    this.loadGenTableList();
  },
  methods: {
    async handleQuery() {
      try {
        this.tableLoading = true;
        const res = await request({
          url: "/tool/gen/list",
          method: "get",
          params: this.queryParams,
        });
        this.tableData = res.list;
        this.total = res.total;
      } finally {
        this.tableLoading = false;
      }
    },
    loadGenTableList() {
      this.handleQuery();
    },
    handlePageChange({ currentPage, pageSize }) {
      this.queryParams.pageNum = currentPage;
      this.queryParams.pageSize = pageSize;
      this.loadGenTableList();
    },
    handlePreview(row) {
      this.previewTableId = row.tableId;
      this.previewModalVisible = true;
      this.previewModalLoading = true;
      this.previewModalLoading = false;
    },
    handleEditTable(row) {
      this.genEditTableId = row.tableId;
      this.editModalVisible = true;
      this.editModalLoading = true;
      this.editModalLoading = false;
    },
    handleDelete(row) {
      const tableIds = row.tableId || this.selectTableIds;
      this.$confirm(
        '是否确认删除表名称为"' + this.selectTableNames + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.tableLoading = true;
          request({
            url: "/tool/gen/" + tableIds,
            method: "delete",
          })
            .then(() => {
              this.tableLoading = false;
              this.loadGenTableList();
              this.msgSuccess("删除成功");
            })
            .catch(() => {
              this.tableLoading = false;
              this.msgSuccess("删除失败");
            });
        })
        .then(() => {})
        .catch(() => {});
    },
    handleSynchDb(row) {
      const tableName = row.tableName;
      this.$confirm('确认要强制同步"' + tableName + '"表结构吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableLoading = true;
          request({
            url: "/tool/gen/synchDb/" + tableName,
            method: "get",
          })
            .then(() => {
              this.msgSuccess("同步成功");
              this.loadGenTableList();
              this.tableLoading = false;
            })
            .catch(() => {
              this.tableLoading = false;
              this.msgSuccess("同步失败");
            });
        })
        .then(() => {})
        .catch(() => {});
    },
    async handleGenTable(row) {
      try {
        const tableNames = row.tableName || this.selectTableNames;
        if (tableNames == "") {
          this.msgError("请选择要生成的数据");
          return;
        }
        this.tableLoading = true;
        if (row.genType === ZIP_GEN_TYPE_KEY) {
          await request({
            url: "/tool/gen/genCode/" + row.tableName,
            method: "get",
          });
          this.msgSuccess("成功生成到自定义路径：" + row.genPath);
        } else {
          await downLoadZip(
            "/tool/gen/batchGenCode?tables=" + tableNames,
            "qm"
          );
        }
      } catch (err) {
        this.msgError("生成代码失败");
      } finally {
        this.tableLoading = false;
      }
    },
    openImportTable() {
      this.importModalVisible = true;
      this.importModalLoading = true;
      this.importModalLoading = false;
    },
    checkboxChangeHandle(v) {
      const { records } = v;
      this.selectTableNames = records.map((item) => item.tableName);
      this.selectTableIds = records.map((item) => item.tableId);
    },
    checkboxAllHandle(v) {
      const { records } = v;
      this.selectTableNames = records.map((item) => item.tableName);
      this.selectTableIds = records.map((item) => item.tableId);
    },
    async importModalConfirm() {
      try {
        this.importModalLoading = true;
        const tableNames = this.importTableSelectRows.map(
          (item) => item.tableName
        );
        if (tableNames.length > 0) {
          await request({
            url: "/tool/gen/importTable",
            method: "post",
            params: { tables: tableNames.join(",") },
          });
          this.handleQuery();
        }
        this.importModalVisible = false;
      } finally {
        this.importModalLoading = false;
      }
    },
    importSelectRowsHandle(selectRows) {
      this.importTableSelectRows = selectRows;
    },
    genEditCloseHandle() {
      this.editModalVisible = false;
      this.handleQuery();
    },
  },
};
</script>

<style scoped lang="scss">
</style>

